package com.cus.tom.transfer.ac;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;

import androidx.annotation.Nullable;

import com.cus.tom.transfer.R;
import com.cus.tom.transfer.bean.Const;
import com.cus.tom.transfer.databinding.ActSendBinding;
import com.cus.tom.transfer.frag.BaseDialogFragment;
import com.cus.tom.transfer.frag.TipDlg;
import com.cus.tom.transfer.trans.service.ReceiveService;
import com.cus.tom.transfer.trans.service.SendService;
import com.cus.tom.transfer.trans.service.TransferService;
import com.cus.tom.transfer.utils.Utils;

import java.io.File;

public class SendAct extends BaseAct {

    ActSendBinding binding;
    int type;

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Const.SEND_SPEED:
                    updateSpeed(intent);
                    break;
                case Const.SEND_OVER:
                    Intent i = new Intent(SendAct.this, OverAct.class);
                    i.putExtra("type", getIntent().getIntExtra("type", 0));
                    i.putExtra("id", intent.getStringExtra("id"));
                    i.putExtras(intent.getExtras());
                    startActivity(i);
                    finish();
                    break;
            }
        }
    };

    private void updateSpeed(Intent i) {
        TransferService.Progress p = i.getParcelableExtra("p");
        long rate = i.getLongExtra("rate", 0);
        binding.name.setText(p.text);
        binding.speed.setText(Utils.formatSize(rate) + "/s");
        binding.bar.setProgress((int) (p.now * 100f / p.max));
        if (rate > 0) {
            float time = (p.max - p.now) * 1f / rate;
            binding.time.setText(String.format("%.1f", time) + "s");
        }
        if (type == 0) {
            if (Utils.getP() == 2) {
                binding.btn.setText("正在发送");
            }
            binding.tip.setText(String.format(getString(R.string.send_num), p.current, p.total));
        } else {
            if (Utils.getP() == 2) {
                binding.btn.setText("正在接收");
            }
            binding.tip.setText(String.format("正在接收第%d个文件", p.current));
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActSendBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        type = getIntent().getIntExtra("type", 0);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Const.SEND_SPEED);
        filter.addAction(Const.SEND_OVER);
        registerReceiver(receiver, filter);

        if (type == 0) {
            binding.tv.setText("正在发送：");
        } else {
            binding.tv.setText("正在接收：");
            binding.btn.setText("取消接收");
            File f = new File(Const.SAVE_DIR);
            if (!f.exists()) {
                f.mkdirs();
            }
            Intent intent = new Intent(this, ReceiveService.class);
            intent.putExtra("path", f.getAbsolutePath());
            String host = getIntent().getStringExtra("host");
            intent.putExtra("host", host);
            startForegroundServiceCompat(intent);
        }

        binding.btn.setOnClickListener(v -> {
            cancel();
        });
    }

    private void startForegroundServiceCompat(Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }

    private void cancel() {
        TipDlg dlg = new TipDlg().setMsg(type == 0 ? "取消发送文件？" : "取消接收文件？").setOk("确定");
        dlg.setOnDismissListener(new BaseDialogFragment.OnDismissListener() {
            @Override
            public void onDismiss(boolean isOk, Object value) {
                if (isOk) {
                    Intent i = new Intent(SendAct.this, type == 0 ? SendService.class : ReceiveService.class);
                    i.setAction("cancel");
                    startService(i);
                    finish();
                }
            }
        });
        dlg.show(getSupportFragmentManager(), "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        if (type == 1) {
            Intent intent = new Intent(this, ReceiveService.class);
            intent.setAction("cancel");
            startService(intent);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
